package com.fanghuaiming.test.netty.c5.eventloop;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import java.net.InetSocketAddress;
import lombok.extern.slf4j.Slf4j;

/****
 * @description:
 * @version:1.0.0
 * @author fanghuaiming
 * @data Created in 2021/9/26 下午9:03
 *
 */
@Slf4j
public class EventLoopFutureListenClient {
  public static void main(String[] args) throws InterruptedException {
      // 2.带有 Future,Promise 的类型都是和异步方法配套使用,用来处理结果
      ChannelFuture channelFuture = new Bootstrap()
              .group(new NioEventLoopGroup())
              .channel(NioSocketChannel.class)
              .handler(new ChannelInitializer<NioSocketChannel>() {
                  @Override
                  protected void initChannel(NioSocketChannel ch) throws Exception {
                      ch.pipeline().addLast(new StringEncoder());
                  }
              })
              //1.发送连接请求
              //异步非阻塞,主线程发起了调用,真正执行连接的是 NioEventLoopGroup 中的一个线程
              .connect(new InetSocketAddress("localhost", 8080));
      //sync是阻塞方法,等待连接完成,如果少了这段代码就直接走下去了,connect线程还没有建立好连接
      //2.1 使用addListener(回调对象) 方法异步处理结果
      channelFuture.addListener(new ChannelFutureListener() {
          //等 NioEventLoopGroup 中的线程建立好连接之后,会调用 operationComplete
          @Override
          public void operationComplete(ChannelFuture future) throws Exception {
              Channel channel = future.channel();
              log.info("===========channel:{}",future.channel());
              channel.writeAndFlush("hello world");
          }
      });
  }
}
